package com.neusoft.springdemo.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.springdemo.bean.Client;

/**
 * 
 * @author chens
 *
 */
@Controller
public class UploadController {
	private Logger logger = Logger.getLogger(UploadController.class);

	@RequestMapping("upload.do")
	public String reg(Client client, HttpSession session, MultipartFile file1)
			throws IllegalStateException, IOException {

		logger.info(client);
		logger.info(file1);
		// 用户提交了文件才执行上传
		if (file1 != null && file1.getSize() != 0) {
			// 服务器上面目录的名称（注意不是开发的工作目录）
			String path = session.getServletContext().getRealPath("/upload");
			// 如果upload上传目录不存在，则创建上传目录
			new File(path).mkdirs();
			// 获取文件的原始名称
			String fileName = file1.getOriginalFilename();
			//使用UUID算法，修改上传后的文件名称
			String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
			// 拼接文件在服务器的存储地址
			File dest = new File(path, newFileName);
			// 执行文件上传，把文件存入服务器
			file1.transferTo(dest);
			logger.info(dest.getAbsolutePath());
			// 上传成功够获取文件的相对地址，并存入服务器s
			client.setHeadImage("upload/" + newFileName);
		}

		session.setAttribute("CLIENT", client);

		return "hello";
	}
}
